#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    vector<vector<int>> ret;
    vector<int> path;
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        dfs(candidates, target, 0, 0);
        return ret;
    }
    void dfs(vector<int>& candidates, int target, int sum, int pos)
    {
        if (sum > target) return;
        if (sum == target)
        {
            ret.push_back(path);
            return;
        }

        for (int i = pos; i < candidates.size(); i++)
        {
            path.push_back(candidates[i]);
            dfs(candidates, target, sum + candidates[i], i);
            path.pop_back();
        }
    }
};

class Solution {
public:
    vector<vector<int>> ret;
    vector<int> path;
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        dfs(candidates, target, 0, 0);
        return ret;
    }
    void dfs(vector<int>& candidates, int target, int pos, int sum)
    {
        if (sum == target)
        {
            ret.push_back(path);
            return;
        }
        if (sum > target || pos == candidates.size()) return;

        for (int i = 0; i <= target / candidates[pos]; i++)
        {
            if (i) path.push_back(candidates[pos]);
            dfs(candidates, target, pos + 1, sum + candidates[pos] * i);
        }
        for (int i = 1; i <= target / candidates[pos]; i++)
        {
            path.pop_back();
        }
    }
};